﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using VoL.Domain.Infrastructure;
using VOL.Entity.DomainModels;
using VOL.WebApi.Common.DTO;
using VOL.WebApi.Common;
using VoL.Domain.IServices;
using VoL.Domain.IServices.BasicData;

namespace VoL.Domain.Services.BasicData
{
    /// <summary>
    /// 科室表服务
    /// </summary>
    public partial class OfficeService : IOfficeService
    {
        /// <summary>
        /// 科室仓储接口
        /// </summary>
        private readonly IBaseRepository<Office> _officeRepository;
        /// <summary>
        /// 病房仓储接口
        /// </summary>
        private readonly IBaseRepository<WardArea> _wardAreaRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="officeRepository">科室仓储接口</param>
        /// <param name="wardAreaRepository">病房仓储接口</param>
        public OfficeService(IBaseRepository<Office> officeRepository, IBaseRepository<WardArea> wardAreaRepository)
        {
            this._officeRepository = officeRepository;
            this._wardAreaRepository = wardAreaRepository;
        }

        /// <summary>
        /// 处理获取科室树形结构的命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public APIResult<List<OfficeDTO>> OfficeHouseTree()
        {
            APIResult<List<OfficeDTO>> res = new APIResult<List<OfficeDTO>>()
            {
                Code = APIEnum.查询成功,
                Message = APIEnum.查询成功.ToString(),
                Data = OfficeTree()
            };
            return res;
        }

        /// <summary>
        /// 获取科室树形结构
        /// </summary>
        /// <returns>返回树形数据</returns>
        private List<OfficeDTO> OfficeTree()
        {
            var officeList = _officeRepository.GetAll().ToList();
            var wardArea = _wardAreaRepository.GetAll().ToList();
            List<OfficeDTO> dto = new List<OfficeDTO>(); //mapper.Map<List<OfficeDTO>>(officeList.ToList());
            foreach (var item in officeList)
            {
                /*
                OfficeDTO officeDTO = new OfficeDTO
                {
                    Id = office.Id,
                    OfficeCode = office.OfficeCode,
                    OfficeName = office.OfficeName,
                    Children = OfficeTree(office.Id)
                };
                officeTree.Add(officeDTO);
                office.Children = OfficeTree(office.Id);
                */
                dto.Add(new OfficeDTO
                {
                    label = item.OfficeName,
                    Children = wardArea.Where(x => x.OfficeCode.Equals(item.OfficeCode)).Select(x => new OfficeDTO { label = x.Name, Id = x.Id }).ToList()
                });
            }
            return dto;
        }
    }
}
